# irremote 32 gpio12 配置在系统中/boot/config.txt
import evdev
import RPi.GPIO as GPIO

LEFT_LED = 7  # 7 GPIO 4
RIGHT_LED   = 40   # 40 GPIO 21


def get_ir_device():
    devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
    for device in devices:
        if (device.name == "gpio_ir_recv"):
            print("Using device", device.path, "\n")
            return device


def get_last_event(dev):
    try:
        for event in dev.read():  # iterate through all queued events
            if (event.value > 0):
                last_event = event
    except BlockingIOError:  # no events to be read
        last_event = None

    return last_event


def get_next_event(dev):
    while(True):
        event = dev.read_one()
        if (event):
            return event


GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()
# 设置GPIO引脚
GPIO.setup(LEFT_LED, GPIO.OUT)
GPIO.setup(RIGHT_LED  , GPIO.OUT)

device = get_ir_device()

try:
    while True:
        next_event = get_next_event(device)
        print(next_event.value)
        if (next_event.value==24):
            GPIO.output(LEFT_LED, GPIO.HIGH)
            GPIO.output(RIGHT_LED  , GPIO.HIGH)

        elif (next_event.value==8):
            GPIO.output(LEFT_LED, GPIO.HIGH)
            GPIO.output(RIGHT_LED  , GPIO.LOW)
        elif (next_event.value==90):
            GPIO.output(LEFT_LED, GPIO.LOW)
            GPIO.output(RIGHT_LED  , GPIO.HIGH)
        elif (next_event.value==82):
            GPIO.output(LEFT_LED, GPIO.LOW)
            GPIO.output(RIGHT_LED  , GPIO.LOW)
except KeyboardInterrupt:  # Ctrl+C
    # 使用结束，释放引脚
    GPIO.cleanup()
